package com.xingqing.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 创建上传目录（使用绝对路径）
        File uploadDirectory = new File(uploadDir).getAbsoluteFile();
        if (!uploadDirectory.exists()) {
            uploadDirectory.mkdirs();
            log.info("创建上传目录: {}", uploadDirectory.getAbsolutePath());
        }
        
        // 配置静态资源访问
        String locationPath = "file:" + uploadDirectory.getAbsolutePath() + "/";
        // 确保路径以正斜杠结尾
        if (!locationPath.endsWith("/")) {
            locationPath += "/";
        }
        
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(locationPath);
        
        log.info("配置文件访问路径: /uploads/** -> {}", locationPath);
    }
}